<template>
  <a-drawer
    title="修改招商公司"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="userEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">

    <a-form :form="form">
      <a-form-item label='公司名称' v-bind="formItemLayout">
        <a-input v-decorator="[
        'brandName',
        { rules: [{ required: true, message: '请输入公司名称!' }] }
        ]"/>
      </a-form-item>
      <a-form-item label='选择图片' v-bind="formItemLayout">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://localhost:9527/web/fileUpload"
          @change="imgHandleChange"
          :before-upload="beforeUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 200px;height: 200px;"/>
          <div v-else>
            <a-icon :type="loadingImg ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>

    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
  import {mapState, mapMutations} from 'vuex'

  const formItemLayout = {
    labelCol: {span: 3},
    wrapperCol: {span: 18}
  }
  export default {
    name: 'UserEdit',
    props: {
      userEditVisiable: {
        default: false
      }
    },
    data() {
      return {
        formItemLayout,
        account: {},
        form: this.$form.createForm(this),
        loadingImg: false,
        imageUrl: '',
        imageName: '',
        deptTreeData: [],
        keychecks: [],
        roleData: [],
        menuKeys: [],
        userDept: [],
        mockData: [],
        targetKeys: [],
        appInfoData: [],
        roleInfoData: [],
        roleKeys: [],
        orgInfoData: [],
        menuInfoData: [],
        userId: '',
        loading: false
      }
    },
    computed: {
      ...mapState({
        currentUser: state => state.account.user
      })
    },
    created() {
      //this.getMock();
      // this.getAppInfo();
      // this.getRoleInfo();
      // this.getMenuInfoByTree();
    },
    methods: {
      ...mapMutations({
        setUser: 'account/setUser'
      }),
      getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      },
      imgHandleChange(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.imageUrl = imageUrl;
            this.imageName = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('You can only upload JPG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      },
      onClose() {
        this.loading = false
        this.form.resetFields()
        this.$emit('close')
      },
      setFormValues({...user}) {
        this.userId = user.id
        let fields = ['brandName']
        Object.keys(user).forEach((key) => {
          if(key === "brandImg") {
            this.imageUrl = "/static/img/image/"+user["brandImg"].toString()
            this.imageName = user["brandImg"].toString()
          }
          if (fields.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = user[key]
            this.form.setFieldsValue(obj)
          }
        })
      },
      onDeptChange(value) {
        this.userDept = value
      },
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.loading = true
            let user = this.form.getFieldsValue()
            user.id = this.userId;
            user.brandImg = this.imageName
            this.$put('/cos/brand-info', {
              ...user
            }).then((r) => {
              this.loading = false
              this.$emit('success')
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
      },
      handleChange(targetKeys, direction, moveKeys) {
        console.log(targetKeys, direction, moveKeys);
        this.targetKeys = targetKeys;
      },
      handleChanges(targetKeys, direction, moveKeys) {
        this.roleKeys = targetKeys;
      },
      handleSearch(dir, value) {
        console.log('search:', dir, value);
      },
      onSelect(keys) {
        this.menuKeys = keys,
          console.log('Trigger Select', keys);
      },
      onCheck(checkedKeys, e) {
        console.log(JSON.stringify(checkedKeys));
      },
      getMessageByOrgId(orgId) {
        this.$get('/power/org-info/info/' + orgId).then((r) => {
          this.menuKeys = [];
          if (r.data.data != undefined) {
            this.targetKeys = r.data.data;
          }
        })
      },
      getMessageByAccount(accountId) {
        this.$get('/power/role-info/info/' + accountId).then((r) => {
          this.menuKeys = [];
          if (r.data.bindMenuInfo != undefined) {
            r.data.bindMenuInfo.forEach((menu) => {
              this.menuKeys.push(parseInt(menu))
            })
          }
          if (r.data.bindAppInfo != undefined) {
            this.targetKeys = r.data.bindAppInfo;
          }
        })
      }
    },
    watch: {
      userEditVisiable() {
        if (this.userEditVisiable) {
          this.$get('role').then((r) => {
            this.roleData = r.data.rows
          })
          this.$get('dept').then((r) => {
            this.deptTreeData = r.data.rows.children
          })
        }
      }
    }
  }
</script>
